package com.cws4cloud.cws.common.mybatis.tenant;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.cws4cloud.cws.common.core.constant.CwsConstant;
import com.cws4cloud.cws.common.core.tenant.CwsTenantProperties;
import com.cws4cloud.cws.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

import java.util.Optional;

/**
 * 租户信息处理器
 *
 * @author zhlj
 */
@Slf4j
@AllArgsConstructor
public class CwsTenantHandler implements TenantLineHandler {

	private final CwsTenantProperties properties;

	/**
	 * 获取租户ID
	 *
	 * @return 租户ID
	 */
	@Override
	public Expression getTenantId() {
		return new StringValue(Optional.ofNullable(SecurityUtils.getTenantId()).orElse(CwsConstant.DEFAULT_TENANT_ID));
	}

	/**
	 * 获取租户字段名称
	 *
	 * @return 租户字段名称
	 */
	@Override
	public String getTenantIdColumn() {
		return properties.getColumn();
	}

	/**
	 * 过滤租户表
	 *
	 * @param tableName 表名
	 * @return 是否忽略, true:表示忽略，false:需要解析并拼接多租户条件
	 */
	@Override
	public boolean ignoreTable(String tableName) {
		return (properties.getIgnoreTables().stream().anyMatch(
				(t) -> t.equalsIgnoreCase(tableName)))
				||(properties.getCwsTables().stream().anyMatch(
				(t) -> t.equalsIgnoreCase(tableName)));
	}
}
